package com.zzw.logtest.log;

import ch.qos.logback.classic.pattern.MessageConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;

public class SensitiveDataConverter extends MessageConverter {
    private int maxLength = 2048;
    private static String converterCanRun = "true";

    //手机号，11位数字，并且前后位不再是数字。
    private static final String PHONE_REGEX = "((?<!\\d)(1[3-9]\\d)\\d{4}(\\d{4})(?!\\d))";

    //身份证
    private static final String IDCARD_REGEX = "((?<!\\d|[a-z]|[A-Z])(\\d{6})\\d{8}(\\d{3}(\\d|X))(?!\\d|[a-z]|[A-Z]))";

    //银行卡号
    private static final String BKCARD_REGEX = "((?<!\\d|[a-z]|[A-Z])(\\d{6})\\d{4,7}(\\d{6})(?!\\d|[a-z]|[A-Z]))";

    //CVV2
    private static final String CVV_REGEX = "((cvn|cvv2|cvn2)\\\"?(\\:|\\=|\\>)\\\"?)(\\d{3})";

    //有效期
    private static final String EDATE_REGEX = "((validDate|valid\\_date|expiredDate|expired)\\\"?(\\:|\\=)\\\"?)(\\d{4}|\\d{2}\\/\\d{2})";

    //姓名
    private static final String NAME_REGEX = "((?i)Name\\\"?(\\:|\\=)\\\"?)([^\\\"]{1})";
    private static final String BASE_ACCT_NO_REGEX = "((?i)ACCT\\_NO\\\"?(\\:|\\=)\\\"?)(.{8})";

    // PIN_REGEX
    private static final String PIN_REGEX = "((IN_CLEAR_TEXT|IN_ENCODE_TEXT|RAN_PASSWORD)\\\"\\:\\\")(.+?)(\\\")";

    @Override
    public String convert(ILoggingEvent event) {
        String oriLogMsg = event.getFormattedMessage();
        String afterLogMsg = invokeMsg(oriLogMsg);
        return afterLogMsg;
    }

    public String invokeMsg(final String oriMsg) {
        String tempMsg = oriMsg;
        int len = tempMsg.length();
        if (len > 20000) {
            tempMsg = tempMsg.substring(0, 400).concat(" ... the logs is too large! the size is: " + len + " ...")
                    .concat(tempMsg.substring(len - 400));
        }

        if ("true".equals(converterCanRun) && tempMsg != null && tempMsg.length() < maxLength) {
            tempMsg = tempMsg.replaceAll(IDCARD_REGEX, "$2********$3");
            tempMsg = tempMsg.replaceAll(BKCARD_REGEX, "$2****$3");
            tempMsg = tempMsg.replaceAll(PHONE_REGEX, "$2****$3");
            tempMsg = tempMsg.replaceAll(CVV_REGEX, "$1***");
            tempMsg = tempMsg.replaceAll(EDATE_REGEX, "$1****");
            tempMsg = tempMsg.replaceAll(NAME_REGEX, "$1*");
            tempMsg = tempMsg.replaceAll(PIN_REGEX, "$1******$4");
            tempMsg = tempMsg.replaceAll(BASE_ACCT_NO_REGEX, "$1********");
        }
        return tempMsg;
    }
}
